const { DataTypes } = require('sequelize');
const { nanoid } = require('nanoid');
const sequelize = require('../config/database');
const MemberCard = require('./MemberCard');

const CardTransaction = sequelize.define('CardTransaction', {
  id: {
    type: DataTypes.STRING,
    primaryKey: true,
    defaultValue: () => nanoid()
  },
  cardId: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '会员卡ID',
    references: {
      model: MemberCard,
      key: 'id'
    }
  },
  type: {
    type: DataTypes.ENUM('充值', '消费'),
    allowNull: false,
    comment: '交易类型'
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: '交易金额（储值卡）'
  },
  times: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '交易次数（次卡）'
  },
  beforeBalance: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: '交易前余额（储值卡）'
  },
  afterBalance: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: '交易后余额（储值卡）'
  },
  beforeTimes: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '交易前次数（次卡）'
  },
  afterTimes: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '交易后次数（次卡）'
  },
  remark: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '交易备注'
  }
}, {
  timestamps: true,
  paranoid: true,
  tableName: 'card_transaction'
});

// 建立与MemberCard的关联关系
CardTransaction.belongsTo(MemberCard, {
  foreignKey: 'cardId',
  as: 'memberCard'
});

MemberCard.hasMany(CardTransaction, {
  foreignKey: 'cardId',
  as: 'transactions'
});

module.exports = CardTransaction;